package datasource;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class HotLineUaDataSource implements IDataSource {
	private static final Logger log = Logger
			.getLogger(HotLineUaDataSource.class);
	private List<String> productsInfo;
	private String categoryURL;
	private Document doc = null;

	public HotLineUaDataSource(String categoryURL) {
		this.categoryURL = categoryURL;
	}

	public List<String> getData() {
		if (productsInfo == null) {
			productsInfo = new ArrayList<String>();
			parsePages();
		}
		return productsInfo;
	}

	private void parsePages() {
		try {
			parseListOfProducts(categoryURL);
			doc = Jsoup.connect(categoryURL).get();
			Elements pages = doc.select("div.pager >span>a");
			for (Element page : pages) {
				parseListOfProducts(categoryURL + page.attr("href"));
			}
		} catch (IOException e) {
			log.error("Wrong url");
		}
	}

	private void parseListOfProducts(String listOfProductsURL)
			throws IOException {
		doc = Jsoup.connect(listOfProductsURL).get();
		Elements productLinks = doc.select("div.title-box > h3 >a");
		for (Element link : productLinks) {
			addProductInfo("http://hotline.ua/" + link.attr("href"));
		}
	}

	private void addProductInfo(String productInfoURL) throws IOException {
		doc = Jsoup.connect(productInfoURL).get();
		String information = doc.select("table.th-info").first().text();
		productsInfo.add(information);

	}

}
